package cn.wsn2018.tools.util;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.model.LoginUser;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 精简化controller的逻辑，将一些固定的设置操作放到此工具类中
 * 将该类设置成线程安全的单例模式
 */
public class ServletUtil {

    private Logger logger = Logger.getLogger(ServletUtil.class);
    private static ServletUtil instance=null;

    public static final HashMap<String,String> operatorTypeMap=new HashMap<String,String>(){
        {
//            put(CommonValue.LOGINMODULE,"系统登录");
//            put(CommonValue.DESIGNMODULE,"请求协议设计接口");
//            put(CommonValue.TESTMODULE,"请求协议测试接口");
//            put(CommonValue.BROWSEMODULE,"请求协议预览接口");
//            put(CommonValue.ERRLOGMODULE,"请求错误日志接口");
//            put(CommonValue.LOGMODULE,"请求业务日志接口");
//            put(CommonValue.WARNINGLOGMODULE,"请求告警日志接口");

            put(CommonValue.LOGINMODULE,"请求系统登录接口");
            put(CommonValue.DESIGNMODULE,"请求协议设计接口");
            put(CommonValue.TESTMODULE,"请求协议测试接口");
            put(CommonValue.BROWSEMODULE,"请求协议预览接口");
            put(CommonValue.ERRLOGMODULE,"请求错误日志接口");
            put(CommonValue.LOGMODULE,"请求业务日志接口");
            put(CommonValue.WARNINGLOGMODULE,"请求告警日志接口");
        }
    };

//    public static HashMap<Long, LoginUser> userMap=null;
//
//    public static HashMap getUserMap(){
//        if (userMap==null)
//            userMap=new HashMap<Long, LoginUser>();
//        return userMap;
//    }
//
//    public static void updateUserMapVal(Long id,LoginUser loginUser){
//        if(userMap==null){
//            userMap=new HashMap<Long, LoginUser>();
//            userMap.put(id,loginUser);
//        }else {
//            Iterator<Map.Entry<Long, LoginUser>> iterator = userMap.entrySet().iterator();
//            while (iterator.hasNext()){
//                Map.Entry<Long, LoginUser> userEntry = iterator.next();
//                LoginUser oldUser = userEntry.getValue();
//                if(oldUser.getUsername().equals(loginUser.getUsername())){
//                    userMap.remove(userEntry.getKey());
//                    break;
//                }
//            }
//            userMap.put(id,loginUser);
//        }
//    }

    //记录当日登录失败次数
    public static HashMap<String,Integer> resMap=null;

    //获取resMap
    public static HashMap getResMap(){
        if(resMap==null){
            resMap=new HashMap<String,Integer>();
        }
        return resMap;
    }

    //获取当前账号填写验证码失败的次数
    public static Integer getFailedNum(String username){
        Integer num = (Integer) getResMap().get(username);
        if(num==null){
            //用户第一次登录失败
            num=new Integer(0);
            getResMap().put(username,0);
        }
        return num;
    }

    //更新用户失败次数
    public static void updateFailedNum(String username,Integer num){
        getResMap().put(username,num);
    }




    private ServletUtil(){}

    /**
     * 得到单例的接口，确保只有一个实例
     * @return
     */
    public static ServletUtil getInstance(){
        if(instance==null){
            synchronized(ServletUtil.class){
                if(instance==null)
                    instance=new ServletUtil();
            }
        }
        return instance;
    }
    /**
     * 处理HttpResponse的一些设置和返回输出操作
     * @param response
     * @param jsonString 从service返回的json字符串
     * @throws Exception
     */
    public void responseOperating(HttpServletResponse response, String jsonString) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-type", "text/html; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Expose-Headers","token");
        response.getWriter().write(jsonString);
    }

    /**
     * 处理HttpRequest的字符集设置操作
     * @param request
     * @throws Exception
     */
    public void requestOperating(HttpServletRequest request)throws Exception{
        request.setCharacterEncoding("utf-8");
    }

    /**
     * @Description:获取ip地址
     * @Param: [request]
     * @return: java.lang.String
     * @Author: SongDaisong
     * @Date: 12:43
     */
    public static String getClientIp(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || ip.indexOf(":") > -1) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                ip = null;
            }
        }
        return ip;
    }
}
